#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
UI工具模块
提供彩色输出和进度条显示功能
"""

import sys
import time
from typing import List, Callable, Any, Optional
from rich.console import Console
from rich.panel import Panel
from rich.progress import Progress, TaskID, TextColumn, BarColumn, TimeRemainingColumn, SpinnerColumn
from rich.text import Text
from rich.table import Table
from rich.style import Style
from rich.box import Box, ROUNDED

# 创建控制台对象
console = Console()

# 预定义样式
STYLES = {
    "info": Style(color="cyan"),
    "success": Style(color="green"),
    "warning": Style(color="yellow"),
    "error": Style(color="red", bold=True),
    "title": Style(color="magenta", bold=True),
    "highlight": Style(color="bright_white", bold=True),
}

# 符号
SYMBOLS = {
    "success": "✅",
    "error": "❌",
    "warning": "⚠️",
    "info": "ℹ️",
    "star": "★",
    "arrow": "➡️",
}

def print_info(message: str) -> None:
    """打印信息消息"""
    console.print(f"{SYMBOLS['info']} {message}", style=STYLES["info"])

def print_success(message: str) -> None:
    """打印成功消息"""
    console.print(f"{SYMBOLS['success']} {message}", style=STYLES["success"])

def print_warning(message: str) -> None:
    """打印警告消息"""
    console.print(f"{SYMBOLS['warning']} {message}", style=STYLES["warning"])

def print_error(message: str) -> None:
    """打印错误消息"""
    console.print(f"{SYMBOLS['error']} {message}", style=STYLES["error"])

def print_title(title: str) -> None:
    """打印带样式的标题"""
    console.print(Panel(title, style=STYLES["title"], box=ROUNDED))

def print_section(title: str) -> None:
    """打印分节标题"""
    console.print(f"\n{SYMBOLS['star']} {title}", style=STYLES["highlight"])

def get_input(prompt: str, default: str = "") -> str:
    """获取用户输入，支持默认值和彩色提示"""
    if default:
        result = console.input(f"[bold cyan]{prompt}[/] [dim][默认: {default}][/]: ")
        return result if result else default
    else:
        return console.input(f"[bold cyan]{prompt}[/]: ")

def confirm(message: str, default: bool = False) -> bool:
    """请求用户确认，支持彩色提示"""
    default_choice = "Y" if default else "N"
    choice = console.input(f"[bold yellow]{message}[/] (Y/N) [dim][默认: {default_choice}][/]: ").strip().upper()
    
    if not choice:
        return default
    
    return choice in ["Y", "YES"]

class ProgressManager:
    """进度条管理器"""
    
    def __init__(self, total: int = 100, description: str = "处理中"):
        """
        初始化进度条管理器
        
        Args:
            total: 任务总量
            description: 任务描述
        """
        self.progress = Progress(
            SpinnerColumn(),
            TextColumn("[bold blue]{task.description}"),
            BarColumn(),
            TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
            TimeRemainingColumn(),
        )
        self.total = total
        self.description = description
        self.task_id = None
    
    def __enter__(self):
        """上下文管理器入口，启动进度条"""
        self.progress.start()
        self.task_id = self.progress.add_task(self.description, total=self.total)
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """上下文管理器退出，停止进度条"""
        if exc_type is None:  # 如果没有发生异常
            self.progress.update(self.task_id, completed=self.total)
        self.progress.stop()
        
    def update(self, advance: int = 1, description: Optional[str] = None):
        """
        更新进度条
        
        Args:
            advance: 前进的步数
            description: 可选的新描述
        """
        if description:
            self.progress.update(self.task_id, advance=advance, description=description)
        else:
            self.progress.update(self.task_id, advance=advance)

def create_menu_table(title: str, options: List[tuple]) -> Table:
    """
    创建美观的菜单表格
    
    Args:
        title: 菜单标题
        options: 选项列表，每个选项为(编号, 名称)元组
        
    Returns:
        格式化的Table对象
    """
    # 创建表格
    table = Table(title=title, box=ROUNDED, highlight=True, header_style="bold magenta")
    
    # 添加列
    table.add_column("选项", style="cyan", no_wrap=True)
    table.add_column("功能描述", style="green")
    
    # 添加行
    for option_id, option_desc in options:
        table.add_row(f"{option_id}", f"{option_desc}")
    
    return table

def with_spinner(func: Callable, message: str = "处理中...") -> Callable:
    """
    为函数添加加载动画装饰器
    
    Args:
        func: 要装饰的函数
        message: 显示的消息
        
    Returns:
        装饰后的函数
    """
    def wrapper(*args, **kwargs):
        with console.status(message, spinner="dots") as status:
            result = func(*args, **kwargs)
        return result
    return wrapper 